package com.lrs.java.spring.core.$03_DependencyInject;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.lrs.java.spring.core.$01_helloworld.HelloApi;

public class BeanInject {

	private static String classpath = "com/lrs/java/spring/core/$03_DependencyInject/beanInject.xml";
	private static BeanFactory beanFactory;
	static {
		beanFactory = new ClassPathXmlApplicationContext(classpath);
	}
	
    //注入其他Bean类型值 通过ref bean
    @Test
    public void testBeanInject() {
        //通过构造器方式注入
        HelloApi bean1 = beanFactory.getBean("bean1", HelloApi.class);
        bean1.sayHello();
        //通过setter方式注入
        HelloApi bean2 = beanFactory.getBean("bean2", HelloApi.class);
        bean2.sayHello();
    }

    
    

    //注入其他Bean类型值 通过ref local/parent
    @Test
    public void testLocalAndparentBeanInject() {
        //初始化父容器
        ApplicationContext parentBeanContext = new ClassPathXmlApplicationContext("com/lrs/java/spring/core/$03_DependencyInject/parentBeanInject.xml");
        //parentBeanContext.getBean("helloApi4LocalParent", HelloApi.class).sayHello();

        //初始化当前容器
        ApplicationContext beanContext = new ClassPathXmlApplicationContext(new String[] {classpath}, parentBeanContext);
        //该Bean引用local bean
        HelloApi beanLocal = beanContext.getBean("beanLocal", HelloApi.class);
        beanLocal.sayHello();
        
        //该Bean引用parent bean
//        HelloApi beanParent = beanContext.getBean("beanParent", HelloApi.class);
//        beanParent.sayHello();
    }
    
    
    
    //注入其他Bean类型值 通过inner bean
    @Test
    public void testInnerBeanInject() {

        HelloApi bean = beanFactory.getBean("outerBean", HelloApi.class);
        bean.sayHello();
    }
    
}
